package actor

import (
	"context"
	"fmt"
	"time"

	"github.com/louloulin/dataflare/pkg/actor/lifecycle"
	"github.com/louloulin/dataflare/pkg/message"
	"github.com/louloulin/dataflare/pkg/plugin"
)

// WasmPluginMessages 定义了WASM插件Actor的消息类型
type WasmPluginMessages struct{}

// ProcessDataMessage 处理数据消息
type ProcessDataMessage struct {
	Data *message.BaseMessage
}

// InitPluginMessage 初始化插件消息
type InitPluginMessage struct {
	Config map[string]interface{}
}

// GetInfoMessage 获取插件信息消息
type GetInfoMessage struct{}

// GetInfoResponse 获取插件信息响应
type GetInfoResponse struct {
	Info plugin.PluginInfo
}

// ProcessResponse 处理响应
type ProcessResponse struct {
	Result *message.BaseMessage
	Error  error
}

// WasmPluginActor 表示一个WASM插件Actor
type WasmPluginActor struct {
	lifecycle.LifecycleAwareActor
	plugin          plugin.Plugin
	processor       plugin.ProcessorPlugin
	lastProcessTime time.Time
	processCount    uint64
	processDuration time.Duration
}

// NewWasmPluginActor 创建一个新的WASM插件Actor
func NewWasmPluginActor(wasmPlugin plugin.Plugin) *WasmPluginActor {
	actor := &WasmPluginActor{
		plugin:       wasmPlugin,
		processCount: 0,
	}

	// 尝试将插件转换为处理器类型
	if proc, ok := wasmPlugin.(plugin.ProcessorPlugin); ok {
		actor.processor = proc
	}

	// 初始化生命周期相关属性
	actor.Initialize(wasmPlugin.ID())

	return actor
}

// OnInit 初始化插件
func (a *WasmPluginActor) OnInit() error {
	// 调用基类方法
	if err := a.LifecycleAwareActor.OnInit(); err != nil {
		return err
	}

	return nil
}

// OnStart 启动插件
func (a *WasmPluginActor) OnStart() error {
	// 调用基类方法
	if err := a.LifecycleAwareActor.OnStart(); err != nil {
		return err
	}

	// 启动WASM插件
	ctx := context.Background()
	if err := a.plugin.Start(ctx); err != nil {
		a.RecordError(err)
		return fmt.Errorf("failed to start WASM plugin: %w", err)
	}

	return nil
}

// OnStop 停止插件
func (a *WasmPluginActor) OnStop() error {
	// 调用基类方法
	if err := a.LifecycleAwareActor.OnStop(); err != nil {
		return err
	}

	// 停止WASM插件
	ctx := context.Background()
	if err := a.plugin.Stop(ctx); err != nil {
		a.RecordError(err)
		return fmt.Errorf("failed to stop WASM plugin: %w", err)
	}

	return nil
}

// HandleProcessMessage 处理数据消息
func (a *WasmPluginActor) HandleProcessMessage(msg *ProcessDataMessage) (*ProcessResponse, error) {
	if !a.IsRunning() {
		return nil, fmt.Errorf("plugin is not running")
	}

	if a.processor == nil {
		return nil, fmt.Errorf("plugin does not implement ProcessorPlugin interface")
	}

	// 处理消息
	a.RecordMessageReceived()
	startTime := time.Now()

	ctx := context.Background()
	result, err := a.processor.Process(ctx, msg.Data)

	// 计算处理时间
	processTime := time.Since(startTime)
	a.processDuration += processTime
	a.lastProcessTime = time.Now()
	a.processCount++

	if err != nil {
		a.RecordError(err)
		return &ProcessResponse{
			Error: fmt.Errorf("failed to process message: %w", err),
		}, nil
	}

	a.RecordMessageSent()
	return &ProcessResponse{
		Result: result.(*message.BaseMessage),
	}, nil
}

// HandleInitMessage 处理初始化消息
func (a *WasmPluginActor) HandleInitMessage(msg *InitPluginMessage) error {
	// 初始化插件
	pluginConfig := &plugin.PluginConfig{
		Config: msg.Config,
	}
	err := a.plugin.Init(context.Background(), pluginConfig)
	if err != nil {
		return fmt.Errorf("failed to initialize WASM plugin: %w", err)
	}

	// 不再在这里启动插件，留给OnStart处理
	return nil
}

// HandleGetInfoMessage 处理获取信息消息
func (a *WasmPluginActor) HandleGetInfoMessage(msg *GetInfoMessage) (*GetInfoResponse, error) {
	// 构建插件信息
	info := plugin.PluginInfo{
		ID:          a.plugin.ID(),
		Name:        a.plugin.Name(),
		Type:        a.plugin.Type(),
		Mode:        plugin.PluginModeWasm,
		Description: a.plugin.Description(),
		Version:     a.plugin.Version(),
		// 其他字段根据需要填充
		Config: a.plugin.Config().Config,
	}

	return &GetInfoResponse{
		Info: info,
	}, nil
}

// GetMetrics 获取插件的指标
func (a *WasmPluginActor) GetMetrics() map[string]interface{} {
	metrics := map[string]interface{}{
		"id":                  a.plugin.ID(),
		"plugin_id":           a.plugin.ID(),
		"plugin_name":         a.plugin.Name(),
		"plugin_type":         string(a.plugin.Type()),
		"plugin_version":      a.plugin.Version(),
		"state":               string(a.State),
		"process_count":       a.processCount,
		"messages_received":   a.Metrics.MessagesReceived,
		"messages_sent":       a.Metrics.MessagesSent,
		"error_count":         a.Metrics.ErrorCount,
		"avg_process_time_ms": float64(a.processDuration.Milliseconds()) / float64(max(a.processCount, 1)),
		"last_process_time":   a.lastProcessTime.Format(time.RFC3339),
	}

	return metrics
}

// String 返回Actor的字符串表示
func (a *WasmPluginActor) String() string {
	return fmt.Sprintf("WasmPluginActor{id=%s, type=%s, state=%s, process_count=%d, messages_received=%d}",
		a.plugin.ID(),
		a.plugin.Type(),
		a.State,
		a.processCount,
		a.Metrics.MessagesReceived)
}

// max 返回两个数中的较大值
func max(a, b uint64) uint64 {
	if a > b {
		return a
	}
	return b
}
